package com.kedll.library;

import android.Manifest;
import android.annotation.SuppressLint;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;

import com.alibaba.android.arouter.launcher.ARouter;
import com.kedll.library.adapter.AbFragmentPagerAdapter;
import com.kedll.library.listener.IHomeDataHelper;
import com.kedll.library.location.LocationInterface;
import com.kedll.library.location.entity.LocationEntity;
import com.kedll.library.location.listener.OnLocationChangeListener;
import com.kedll.library.util.Exit;
import com.kedll.library.widget.AbViewPager;
import com.kedll.library.widget.MyTabBar;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 此类用于当主界面已底部导航栏的方式时,使用者需要实现IHomeDataHelper接口,
 * 同时继承此类,实现getDataHelper虚方法,比如
 * MyHomeDataHelper implements IHomeDataHelper;
 *
 * @author QiQi
 * @Override protected IHomeDataHelper getDataHelper(){
 * return new MyHomeDataHelper;
 * }
 * <p/>
 * Created by QiQi on 15/12/15.
 */
@RuntimePermissions
public abstract class AbstractMainActivity<V extends ViewDataBinding> extends KBaseActivity<V> implements OnLocationChangeListener {

    /**
     * 从左到右的Fragment名字,格式为PackageName + ClassName
     */
    protected String[] classes;

    protected int selectTag = 0;
    protected IHomeDataHelper dataHelper;
    protected AbViewPager mViewPager;
    //    protected BottomNavigationView lowBar;
    protected MyTabBar lowBar;
    protected LocationInterface proxy;
    AbFragmentPagerAdapter mAdapter;
    private Exit exit;

    public Fragment getCurrentFragment() {
        return mAdapter.getItem(getCurrentItem());
    }

    /**
     * 获取当前界面
     *
     * @return
     */
    public int getCurrentItem() {
        return mViewPager.getCurrentItem();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @SuppressLint("CheckResult")
    @Override
    @CallSuper
    protected void initData(Bundle savedInstanceState) {
        MobclickAgent.openActivityDurationTrack(false);

        proxy = getLocationInterface();
        if (proxy != null) {
            AbstractMainActivityPermissionsDispatcher.requestLocationWithPermissionCheck(this);
        }

        if (savedInstanceState != null) {
            selectTag = savedInstanceState.getInt("position");
        }

        IHomeDataHelper dataHelper = getDataHelper();
        classes = dataHelper.getFragmentName();
        int size = classes.length;
        List<Fragment> fragments = new ArrayList<>();
        for (String aClass : classes) {
            Fragment fragment = (Fragment) ARouter.getInstance().build(aClass).navigation();
            fragments.add(fragment);
        }

        mViewPager = findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(size);
        mAdapter = new AbFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setPagingEnabled(false);

        lowBar = findViewById(R.id.lowBar);
        lowBar.setNormalTextColor(dataHelper.getNormalTextColor());
        lowBar.setSelectTextColor(dataHelper.getSelectTextColor());
        lowBar.setResources(dataHelper.getTabBarNormalIcon(), dataHelper.getTabBarPressIcon(), dataHelper.getTabMenuName(this));
        lowBar.setCurrentItem(selectTag);
//        lowBar.initForMenu(getMenuResId());
//        lowBar.setItemTextColor(ContextCompat.getColorStateList(getApplicationContext(), R.color.tab_item_text_color));
//        lowBar.setItemIconTint(ContextCompat.getColorStateList(getApplicationContext(), R.color.tab_item_text_color));

//        lowBar.setSelection(selectTag);
    }

    @Override
    protected void initEvent() {
        lowBar.setOnTabSelectListener(new MyTabBar.OnTabSelectListener() {
            @Override
            public void onSelection(int position) {
                mViewPager.setCurrentItem(position, false);
            }
        });

//        lowBar.setOnNavigationItemSelectedListener(item -> {
//            selectTag = getSelection(item.getItemId());
//            mViewPager.setCurrentItem(selectTag, false);
//            return true;
//        });
    }

    /**
     * 把底部导航栏中的menuId转换成对应的选项
     *
     * @param itemId
     * @return
     */
//    protected abstract int getSelection(int itemId);
    @Override
    protected void onDestroy() {
        super.onDestroy();
        exit();
        dataHelper = null;
        exit = null;
        if (proxy != null) {
            proxy.stopLocation();
            proxy = null;
        }
    }

    protected void exit() {
        //TODO 处理退出应用后的一些操作,比如退出登录
        MobclickAgent.onKillProcess(this);
        System.gc();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AbstractMainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    /**
     * 获取定位的实现
     *
     * @return
     */
    protected abstract LocationInterface getLocationInterface();

    /**
     * 获取首页界面的相关元素，比如底部导航栏的名字及图标，Fragment的class name
     *
     * @return
     */
    protected abstract IHomeDataHelper getDataHelper();

    /**
     * 获取底部导航栏Menu
     *
     * @return
     */
//    @MenuRes
//    protected abstract int getMenuResId();
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("position", selectTag);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (exit == null) {
                exit = new Exit(this);
            }
            exit.pressAgainExit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置角标
     *
     * @param count
     * @param position
     */
    protected void setMark(int count, int position) {
    }

    @Override
    public void onLocationChangeListener(LocationEntity entity) {
        KBaseApplication app = (KBaseApplication) getApplication();
        app.setLocation(entity);
        proxy.stopLocation();
    }

    @NeedsPermission({Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE})
    void requestLocation() {
        if (proxy != null) {
            proxy.startLocation(0);
        }
    }
}
